package com.rockcent.mall.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.RDateUtils;
import com.rockcent.mall.Routes;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.MarketMerchantCooperationStatus;
import com.rockcent.mall.lib.domain.enumclass.MarketMerchantProductSalesStatus;
import com.rockcent.mall.lib.domain.enumclass.MerchantCooperationType;
import com.rockcent.mall.lib.domain.enumclass.ProductStatus;
import com.rockcent.mall.lib.dto.MarketMerchantCooperationDto;
import com.rockcent.mall.lib.dto.MarketMerchantProductSalesDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.*;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by HK on 16/8/16.
 * <p>
 * 商家合作关系管理
 */
@RestController
public class MarketMerchantCooperationController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(MarketMerchantCooperationController.class);

    @Autowired
    private BaseUserHelper userHelper;
    @Autowired
    private MarketMerchantCooperationRepository marketMerchantCooperationRepository;
    @Autowired
    private MarketMerchantCooperationRecordRepository marketMerchantCooperationRecordRepository;
    @Autowired
    private MarketMerchantCooperationMessageRepository marketMerchantCooperationMessageRepository;
    @Autowired
    private MerchantRepository merchantRepository;
    @Autowired
    private MarketMerchantProductSalesRepository marketMerchantProductSalesRepository;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private MerchantProductRepository merchantProductRepository;

    /**
     * @api {get} /market/merchant/cooperation/work_count 商家合作管理 数量统计
     * @apiGroup market_merchant_cooperation
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiSuccess supplierCooperationCount 供应商 合作数
     * @apiSuccess distributorCooperationCount 分销商 合作数
     * @apiSuccess supplierRecordCount 供应商 申请记录数
     * @apiSuccess distributorRecordCount 分销商 待审核记录数
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * "data": {
     *      "supplierRecordCount": 0,
     *      "distributorCount": 0,
     *      "distributorRecordCount": 0,
     *      "supplierCooperationCount": 0
     *  }
     * }
     */
    @RequestMapping(value = Routes.MARKET_MERCHANT_COOPERATION_WORK_COUNT, method = RequestMethod.GET)
    public JsonResult cooperationWorkCount(HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            // 供应商 合作数
            Long merchantId = userInfoDto.merchant.getId();
            Long supplierCooperationCount = marketMerchantCooperationRepository.countByDistributorMerchantIdAndStatus(merchantId, MarketMerchantCooperationStatus.PASS);
            // 分销商 合作数
            Long distributorCooperationCount = marketMerchantCooperationRepository.countBySupplierMerchantIdAndStatus(merchantId, MarketMerchantCooperationStatus.PASS);
            // 供应商 申请记录数
            Long supplierRecordCount = marketMerchantCooperationRecordRepository.countByDistributorMerchantId(merchantId);
            // 分销商 待审核记录数
            Long distributorRecordCount = marketMerchantCooperationRecordRepository.countBySupplierMerchantIdAndStatus(merchantId, MarketMerchantCooperationStatus.WAIT);
            Map<String, Long> countData = new HashMap<>();
            countData.put("supplierCooperationCount", supplierCooperationCount);
            countData.put("distributorCooperationCount", distributorCooperationCount);
            countData.put("supplierRecordCount", supplierRecordCount);
            countData.put("distributorRecordCount", distributorRecordCount);
            jsonResult.data = countData;
        };
        return doing.go(userInfoDto, request, objectMapper, log);
    }


    /**
     * @api {get} /market/merchant/cooperation/work_page 商家合作管理 合作中 分页
     * @apiGroup market_merchant_cooperation
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {String=SUPPLIER("供应商"), DISTRIBUTOR("分销商")} type <code>必须参数</code> 类型
     * @apiParam {String} searchMerchantName 搜索:商家名称
     * @apiParam {String} searchStartTime 搜索:开始时间
     * @apiParam {String} searchEndTime 搜索:结束时间
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": {
     *      "data": [
     *          {
     *              "id": 1,
     *              "dateCreated": "2016-09-14 17:22:22",
     *              "lastUpdated": "2016-09-28 11:33:54",
     *              "supplierMallId": 1,
     *              "supplierMerchantId": 2,
     *              "distributorMallId": 1,
     *              "distributorMerchantId": 1,
     *              "supplierMerchantName": "b1测试商户 X",
     *              "status": "PASS"
     *          },
     *          ...
     *      ],
     *      "totalCount": 1,
     *      "totalPage": 1,
     *      "pageNo": 0,
     *      "pageSize": 10,
     *      "url": "/market/merchant/cooperation/work_page",
     *      "prevUrl": "/market/merchant/cooperation/work_page?pageNo=0&pageSize=10",
     *      "nextUrl": "/market/merchant/cooperation/work_page?pageNo=0&pageSize=10"
     *  }
     * }
     */
    @RequestMapping(value = Routes.MARKET_MERCHANT_COOPERATION_WORK_PAGE, method = RequestMethod.GET)
    public JsonResult<PageResult<MarketMerchantCooperationDto>> workPage(MarketMerchantCooperationDto marketMerchantCooperationDto, HttpServletRequest request, HttpServletResponse response) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing<PageResult<MarketMerchantCooperationDto>> doing = jsonResult -> {

            String marketMerchantCooperationDtoType = marketMerchantCooperationDto.getType();
            if (StringUtils.isBlank(marketMerchantCooperationDtoType)) {
                jsonResult.errorParam(MarketMerchantCooperation.CHECK_TYPE_IS_NOT_NULL,log);
                return;
            }

            if (!EnumUtils.isValidEnum(MerchantCooperationType.class, marketMerchantCooperationDtoType)) {
                jsonResult.errorParam(MarketMerchantCooperation.CHECK_TYPE_ALLOW,log);
                return;
            }
            if (StringUtils.isNotBlank(marketMerchantCooperationDto.getSearchStartTime()) && RDateUtils.isNotDate(marketMerchantCooperationDto.getSearchStartTime())) {
                jsonResult.remind("日期格式不正确,允许格式:" + RDateUtils.parsePattern,log);
                return;
            }
            if (StringUtils.isNotBlank(marketMerchantCooperationDto.getSearchEndTime()) && RDateUtils.isNotDate(marketMerchantCooperationDto.getSearchEndTime())) {
                jsonResult.remind("日期格式不正确,允许格式:" + RDateUtils.parsePattern,log);
                return;
            }

            Long merchantId = userInfoDto.merchant.getId();
            PageResult<MarketMerchantCooperationDto> pageResult = marketMerchantCooperationRepository.findPage(merchantId, marketMerchantCooperationDto, this.getPage(marketMerchantCooperationDto.getPageNo(), marketMerchantCooperationDto.getPageSize()));
            pageResult.setUrl(Routes.MARKET_MERCHANT_COOPERATION_WORK_PAGE);
            pageResult.data.stream().map(dto -> {
                Long productSalesCount = 0L;
                if (MerchantCooperationType.DISTRIBUTOR == MerchantCooperationType.valueOf(marketMerchantCooperationDtoType)) {
                    Long distributorMerchantId = dto.getDistributorMerchantId();
                    productSalesCount = marketMerchantProductSalesRepository.countBySupplierMerchantIdAndDistributorMerchantIdAndSupplierStatusAndDistributorStatus(merchantId, distributorMerchantId, MarketMerchantProductSalesStatus.PASS, MarketMerchantProductSalesStatus.PASS);
                } else if (MerchantCooperationType.SUPPLIER == MerchantCooperationType.valueOf(marketMerchantCooperationDtoType)) {
                    Long supplierMerchantId = dto.getSupplierMerchantId();
                    productSalesCount = marketMerchantProductSalesRepository.countBySupplierMerchantIdAndDistributorMerchantIdAndSupplierStatusAndDistributorStatus(supplierMerchantId, merchantId, MarketMerchantProductSalesStatus.PASS, MarketMerchantProductSalesStatus.PASS);
                }
                dto.setProductSalesCount(productSalesCount);
                return dto;
            }).collect(Collectors.toList());


            jsonResult.data = pageResult;
        };
        return doing.go(userInfoDto, request, objectMapper, log);
    }


    /**
     * @api {post} /market/merchant/cooperation/work_stop 商家合作管理 合作终止
     * @apiGroup market_merchant_cooperation
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {Long} workStopMerchantId <code>必须参数</code> 终止合作商家 id
     * @apiParam {String=SUPPLIER("供应商"), DISTRIBUTOR("分销商")} type <code>必须参数</code> 类型
     * @apiSuccessExample {json} Success-Response:
     * {
     *      "code": "1",
     *      "desc": "成功"
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MARKET_MERCHANT_COOPERATION_WORK_STOP, method = RequestMethod.POST)
    public JsonResult workStop(@RequestBody MarketMerchantCooperationDto marketMerchantCooperationDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Long workStopMerchantId = marketMerchantCooperationDto.getWorkStopMerchantId();
            if (workStopMerchantId == null) {
                jsonResult.errorParam("workStopMerchantId 不能为空", log);
                return;
            }

            String marketMerchantCooperationDtoType = marketMerchantCooperationDto.getType();
            if (StringUtils.isBlank(marketMerchantCooperationDtoType)) {
                jsonResult.errorParam(MarketMerchantCooperation.CHECK_TYPE_IS_NOT_NULL,log);
                return;
            }

            if (!EnumUtils.isValidEnum(MerchantCooperationType.class, marketMerchantCooperationDtoType)) {
                jsonResult.errorParam(MarketMerchantCooperation.CHECK_TYPE_ALLOW,log);
                return;
            }
            MarketMerchantCooperation marketMerchantCooperation = null;

            // 主动人 分销商
            Long merchantId = userInfoDto.merchant.getId();
            if (MerchantCooperationType.valueOf(marketMerchantCooperationDtoType) == MerchantCooperationType.SUPPLIER) {
                marketMerchantCooperation = marketMerchantCooperationRepository.findBySupplierMerchantIdAndDistributorMerchantIdAndStatusNot(workStopMerchantId,merchantId,  MarketMerchantCooperationStatus.REFUSE);
            } else if (MerchantCooperationType.valueOf(marketMerchantCooperationDtoType) == MerchantCooperationType.DISTRIBUTOR) {
                // 主动人 供应商
                marketMerchantCooperation = marketMerchantCooperationRepository.findBySupplierMerchantIdAndDistributorMerchantIdAndStatusNot(merchantId, workStopMerchantId, MarketMerchantCooperationStatus.REFUSE);
            }
            if (marketMerchantCooperation == null || marketMerchantCooperation.getStatus() != MarketMerchantCooperationStatus.PASS) {
                jsonResult.remind("与供应商没有达成合作关系",log);
                return;
            }

            marketMerchantCooperation.setStatus(MarketMerchantCooperationStatus.REFUSE);
            marketMerchantCooperationRepository.save(marketMerchantCooperation);

            // 把所有分销产品全部统一下架,且不能再上架
            Long supplierMerchantId = marketMerchantCooperation.getSupplierMerchantId();
            Long distributorMerchantId = marketMerchantCooperation.getDistributorMerchantId();
            List<MarketMerchantProductSales> marketMerchantProductSalesList = marketMerchantProductSalesRepository.findBySupplierMerchantIdAndDistributorMerchantIdAndIsDelete(supplierMerchantId, distributorMerchantId, Whether.NO);
            marketMerchantProductSalesList.forEach(marketMerchantProductSales -> {
                // 把所有合作的商品,双方状态更改为拒绝状态
                marketMerchantProductSales.setIsDelete(Whether.YES);
                marketMerchantProductSales.setDistributorStatus(MarketMerchantProductSalesStatus.REFUSE);
                marketMerchantProductSales.setSupplierStatus(MarketMerchantProductSalesStatus.REFUSE);
                marketMerchantProductSalesRepository.save(marketMerchantProductSales);
                Long marketDistributorMerchantId = marketMerchantProductSales.getDistributorMerchantId();
                Long marketMerchantProductSalesProductId = marketMerchantProductSales.getProductId();
                List<Product> marketProductList = merchantProductRepository.findByMerchantIdAndMarketIdAndStatusIn(marketDistributorMerchantId, marketMerchantProductSalesProductId, Arrays.asList(ProductStatus.SELLING, ProductStatus.SOLDOUT, ProductStatus.EXPIRED));
                // 分销商终止合作
                if (MerchantCooperationType.valueOf(marketMerchantCooperationDtoType) == MerchantCooperationType.SUPPLIER) {
                    for (Product product : marketProductList) {
                        product.setStatus(ProductStatus.DISTRIBUTOR_COOPERATION_STOP);
                        product.setIsDelete(Whether.YES);
                        merchantProductRepository.save(product);
                    }
                } else if (MerchantCooperationType.valueOf(marketMerchantCooperationDtoType) == MerchantCooperationType.DISTRIBUTOR) {
                    // 供应商终止合作
                    for (Product marketProduct : marketProductList) {
                        marketProduct.setStatus(ProductStatus.SUPPLIER_COOPERATION_STOP);
                        marketProduct.setIsDelete(Whether.YES);
                        merchantProductRepository.save(marketProduct);
                    }
                }
            });

            // 发送分销消息
            if (MerchantCooperationType.valueOf(marketMerchantCooperationDtoType) == MerchantCooperationType.SUPPLIER) {
                // 发送分销消息
                // 终止成功 发送对象 分销商
                Merchant distributorMerchant = merchantRepository.findOne(marketMerchantCooperation.getDistributorMallId());
                Merchant supplierMerchant = merchantRepository.findOne(supplierMerchantId);

                MarketMerchantCooperationMessage supplierMarketMerchantCooperationMessage = new MarketMerchantCooperationMessage();
                supplierMarketMerchantCooperationMessage.setMerchantId(distributorMerchant.getId());
                supplierMarketMerchantCooperationMessage.setTitle("终止成功");
                String supplierMerchantName = supplierMerchant.getName();
                supplierMarketMerchantCooperationMessage.setContent(String.format("尊敬的客户，您与供应商%s的分销合作关系已终止成功，请知悉。", supplierMerchantName));
                marketMerchantCooperationMessageRepository.save(supplierMarketMerchantCooperationMessage);

                // 终止合作 发送对象 供应商
                MarketMerchantCooperationMessage distributorMarketMerchantCooperationMessage = new MarketMerchantCooperationMessage();
                distributorMarketMerchantCooperationMessage.setMerchantId(supplierMerchant.getId());
                distributorMarketMerchantCooperationMessage.setTitle("终止合作");
                String distributorMerchantName = distributorMerchant.getName();
                distributorMarketMerchantCooperationMessage.setContent(String.format("尊敬的客户，分销商%s已单方面终止跟您的合作关系，相应的产品已经从该分销商商户内下架处理，请知悉。", distributorMerchantName));
                marketMerchantCooperationMessageRepository.save(distributorMarketMerchantCooperationMessage);
            } else if (MerchantCooperationType.valueOf(marketMerchantCooperationDtoType) == MerchantCooperationType.DISTRIBUTOR) {
                // 发送分销消息
                Merchant distributorMerchant = merchantRepository.findOne(distributorMerchantId);
                Merchant supplierMerchant = merchantRepository.findOne(supplierMerchantId);

                // 终止合作 发送对象 分销商
                MarketMerchantCooperationMessage distributorMarketMerchantCooperationMessage = new MarketMerchantCooperationMessage();
                distributorMarketMerchantCooperationMessage.setMerchantId(distributorMerchant.getId());
                distributorMarketMerchantCooperationMessage.setTitle("终止合作");
                String supplierMerchantName = supplierMerchant.getName();
                distributorMarketMerchantCooperationMessage.setContent(String.format("尊敬的客户，供应商%s已单方面终止跟您的合作关系，相应的产品已经从商户内下架处理，请知悉。", supplierMerchantName));
                marketMerchantCooperationMessageRepository.save(distributorMarketMerchantCooperationMessage);

                // 终止成功 发送对象 供应商
                MarketMerchantCooperationMessage supplierMarketMerchantCooperationMessage = new MarketMerchantCooperationMessage();
                supplierMarketMerchantCooperationMessage.setMerchantId(supplierMerchant.getId());
                supplierMarketMerchantCooperationMessage.setTitle("终止成功");
                String distributorMerchantName = distributorMerchant.getName();
                supplierMarketMerchantCooperationMessage.setContent(String.format("尊敬的客户，您与分销商%s的分销合作关系已终止成功，请知悉。", distributorMerchantName));
                marketMerchantCooperationMessageRepository.save(supplierMarketMerchantCooperationMessage);
            }


        };
        return doing.go(userInfoDto, request, objectMapper, log);
    }

    /**
     * @api {get} /market/merchant/cooperation/work_product_list 商家合作管理 合作中 产品列表
     * @apiGroup market_merchant_cooperation
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {String=SUPPLIER("供应商"), DISTRIBUTOR("分销商")} type <code>必须参数</code> 类型
     *
     * @apiParam {Long} distributorMerchantId <code>当 type = DISTRIBUTOR,必须参数</code> 分销商id
     * @apiParam {Long} supplierMerchantId <code>当 type = SUPPLIER,必须参数</code> 供应商id
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": [
     *          {
     *          "id": 32,
     *          "dateCreated": 1476007416000,
     *          "lastUpdated": 1476169525000,
     *          "productId": "112",
     *          "supplierMallId": 1,
     *          "supplierMerchantId": 1,
     *          "supplierStatus": "PASS",
     *          "distributorMerchantId": 2,
     *          "distributorStatus": "PASS",
     *          "productName": "aaaa",
     *          "productBasePrice": 132.0,
     *          "productSellPrice": 144.0,
     *          "productQuantity": 1,
     *          "productType":"GOODS",
     *          "productStatus": "SELLING",
     *          "productStatusText": "在售"
     *      },
     *      ...
     *  ]
     * }
     */
    @RequestMapping(value = Routes.MARKET_MERCHANT_COOPERATION_WORK_PRODUCT_LIST, method = RequestMethod.GET)
    public JsonResult workProductList(MarketMerchantCooperationDto marketMerchantCooperationDto, HttpServletRequest request, HttpServletResponse response) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {

            String marketMerchantCooperationDtoType = marketMerchantCooperationDto.getType();
            if (StringUtils.isBlank(marketMerchantCooperationDtoType)) {
                jsonResult.errorParam(MarketMerchantCooperation.CHECK_TYPE_IS_NOT_NULL,log);
                return;
            }

            if (!EnumUtils.isValidEnum(MerchantCooperationType.class, marketMerchantCooperationDtoType)) {
                jsonResult.errorParam(MarketMerchantCooperation.CHECK_TYPE_ALLOW,log);
                return;
            }

            List<MarketMerchantProductSalesDto> marketMerchantProductSalesDtoList = null;
            Long merchantId = userInfoDto.merchant.getId();
            if (MerchantCooperationType.valueOf(marketMerchantCooperationDtoType) == MerchantCooperationType.DISTRIBUTOR) {
                Long distributorMerchantId = marketMerchantCooperationDto.getDistributorMerchantId();
                if (distributorMerchantId == null) {
                    jsonResult.errorParam(MarketMerchantCooperation.CHECK_DISTRIBUTOR_MERCHANT_ID_IS_NOT_NULL,log);
                    return;
                }
                marketMerchantProductSalesDtoList = marketMerchantProductSalesRepository.findDtoByDistributorMerchantIdAndSupplierMerchantIdAndIsDelete(MerchantCooperationType.DISTRIBUTOR, distributorMerchantId, merchantId, Whether.NO.toString());

                // TODO: 16/10/9 销售情况没有完成
            } else if (MerchantCooperationType.valueOf(marketMerchantCooperationDtoType) == MerchantCooperationType.SUPPLIER) {
                Long supplierMerchantId = marketMerchantCooperationDto.getSupplierMerchantId();
                if (supplierMerchantId == null) {
                    jsonResult.errorParam(MarketMerchantCooperation.CHECK_SUPPLIER_MERCHANT_ID_IS_NOT_NULL,log);
                    return;
                }
                marketMerchantProductSalesDtoList = marketMerchantProductSalesRepository.findDtoByDistributorMerchantIdAndSupplierMerchantIdAndIsDelete(MerchantCooperationType.SUPPLIER, merchantId, supplierMerchantId, Whether.NO.toString());
                // TODO: 16/10/9 销售情况没有完成
            }
            jsonResult.data = marketMerchantProductSalesDtoList;

        };
        return doing.go(userInfoDto, request, objectMapper, log);
    }

    /**
     * @api {post} /market/merchant/cooperation/work_product_cancel 商家合作管理 合作中 取消供货/取消分销
     * @apiGroup market_merchant_cooperation
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {String=SUPPLIER("供应商"), DISTRIBUTOR("分销商")} type <code>必须参数</code> 类型
     *
     * @apiParam {Long} distributorMerchantId <code>当 type = DISTRIBUTOR,必须参数</code> 分销商id
     * @apiParam {Long} supplierMerchantId <code>当 type = SUPPLIER,必须参数</code> 供应商id
     * @apiParam {Long} productId <code>必须参数</code> 产品id
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功"
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MARKET_MERCHANT_COOPERATION_WORK_PRODUCT_CANCEL, method = RequestMethod.POST)
    public JsonResult workProductCancel(@RequestBody MarketMerchantCooperationDto marketMerchantCooperationDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        log.info("======================>marketMerchantCooperationDto:"+marketMerchantCooperationDto);
        RestDoing doing = jsonResult -> {
            String marketMerchantCooperationDtoType = marketMerchantCooperationDto.getType();
            if (StringUtils.isBlank(marketMerchantCooperationDtoType)) {
                jsonResult.errorParam(MarketMerchantCooperation.CHECK_TYPE_IS_NOT_NULL, log);
                return;
            }

            if (!EnumUtils.isValidEnum(MerchantCooperationType.class, marketMerchantCooperationDtoType)) {
                jsonResult.errorParam(MarketMerchantCooperation.CHECK_TYPE_ALLOW, log);
                return;
            }

            Long productId = marketMerchantCooperationDto.getProductId();
            if (productId == null) {
                jsonResult.errorParam(Product.CHECK_ID_IS_NOT_NULL, log);
                return;
            }


            Long merchantId = userInfoDto.merchant.getId();
            if (MerchantCooperationType.valueOf(marketMerchantCooperationDtoType) == MerchantCooperationType.DISTRIBUTOR) {
                Long distributorMerchantId = marketMerchantCooperationDto.getDistributorMerchantId();
                if (distributorMerchantId == null) {
                    jsonResult.errorParam(MarketMerchantCooperation.CHECK_DISTRIBUTOR_MERCHANT_ID_IS_NOT_NULL, log);
                    return;
                }

                Long marketId = productId;
                Product product = merchantProductRepository.queryByMarketIdAndMerchantIdAndIsDeleteNotInExpired(marketId,distributorMerchantId, Whether.NO);
                log.info("======================>product:"+product);
                if (product == null) {
                    jsonResult.remind("该产品没有和分销商建立合作关系", log);
                    return;
                }

                productId = product.getMarketId();

                MarketMerchantProductSales marketMerchantProductSales = marketMerchantProductSalesRepository.findByProductIdAndSupplierMerchantIdAndDistributorMerchantIdAndIsDeleteInPass(productId, merchantId, distributorMerchantId, Whether.NO);
                log.info("======================>marketMerchantProductSales:"+marketMerchantProductSales);
                if (marketMerchantProductSales == null) {
                    jsonResult.remind("该产品没有和分销商建立合作关系", log);
                    return;
                }


                // 取消供货
                product.setStatus(ProductStatus.SUPPLIER_CANCEL_SOLDOUT);
                product.setIsDelete(Whether.YES);
                merchantProductRepository.save(product);
                marketMerchantProductSales.setSupplierStatus(MarketMerchantProductSalesStatus.REFUSE);
                marketMerchantProductSalesRepository.save(marketMerchantProductSales);
            } else if (MerchantCooperationType.valueOf(marketMerchantCooperationDtoType) == MerchantCooperationType.SUPPLIER) {
                Long supplierMerchantId = marketMerchantCooperationDto.getSupplierMerchantId();
                if (supplierMerchantId == null) {
                    jsonResult.errorParam(MarketMerchantCooperation.CHECK_SUPPLIER_MERCHANT_ID_IS_NOT_NULL, log);
                    return;
                }
                Product product = merchantProductRepository.findByMarketIdAndMerchantIdAndIsDelete(productId, merchantId, Whether.NO);

                if (product == null) {
                    jsonResult.remind("该产品没有和供应商建立合作关系", log);
                    return;
                }
                log.info("======================>product:"+product);
                MarketMerchantProductSales marketMerchantProductSales = marketMerchantProductSalesRepository.findByProductIdAndDistributorMerchantIdAndSupplierMerchantIdAndIsDeleteAndDistributorStatus(productId, merchantId, supplierMerchantId, Whether.NO, MarketMerchantProductSalesStatus.PASS);
                if (marketMerchantProductSales == null) {
                    jsonResult.remind("该产品没有和供应商建立合作关系",log);
                    return;
                }
                log.info("======================>marketMerchantProductSales:"+marketMerchantProductSales);
                // 取消分销
                product.setStatus(ProductStatus.DISTRIBUTOR_CANCEL_SOLDOUT);
                product.setIsDelete(Whether.YES);
                merchantProductRepository.save(product);
                marketMerchantProductSales.setDistributorStatus(MarketMerchantProductSalesStatus.REFUSE);
                marketMerchantProductSalesRepository.save(marketMerchantProductSales);
            }
        };
        return doing.go(userInfoDto, request, objectMapper, log);
    }

}
